import gunicorn.app.base


class WSGIApplication(gunicorn.app.base.BaseApplication):
    def __init__(self, app, options=None):
        self.options = options or {}
        self.application = app
        super().__init__()

    def load_config(self):
        config = {
            key: value
            for key, value in self.options.items()
            if key in self.cfg.settings and value is not None
        }
        for key, value in config.items():
            self.cfg.set(key.lower(), value)

    def load(self):
        return self.application


if __name__ == "__main__":
    from smartcab.perm import init_permission_system
    from dotenv import load_dotenv

    import os
    import smartcab
    import multiprocessing

    from smartcab.data import db

    load_dotenv()

    SERVER_FALLBACK_PORT = 80
    SERVER_PORT = os.getenv("SERVER_PORT", SERVER_FALLBACK_PORT)
    WORKERS = (multiprocessing.cpu_count() * 2) + 1

    init_permission_system()

    db.global_init()

    WSGIApplication(
        smartcab.make_app(),
        {"bind": f"0.0.0.0:{SERVER_PORT}", "workers": WORKERS},
    ).run()
